package controller;

import DAO.BaseDAO;
import DAO.ProjectDAO;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.http.HttpSession;
import model.Category;
import model.Metric_User;
import model.Project;
import model.User;
import org.apache.commons.mail.EmailException;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

@ManagedBean(name = "projectController")
@SessionScoped
public class ProjectController {

    private int SelectCategory;
    public Project project;
    private TreeNode root;
    private String Node;
    private boolean display = false;
    public DataModel listProject;

    public ProjectController() {
        project = new Project();
    }

    public String updateProject() {
        BaseDAO dao = new ProjectDAO();
        dao.update(project);
        setProject(new Project());
        return "#";
    }

    public void saveProject() throws EmailException {
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        User u = (User) session.getAttribute("user");
        project.setUserId(u.getId());
        System.out.println("GETID>>>>"+u);
        String localFile = (String) session.getAttribute("localFile");
        project.setLocalFiles("/home/odiar/Public/file/" + u.getEmail() + "/" + project.getName() + "/");
        BaseDAO dao = new ProjectDAO();
        dao.save(project);
        session.setAttribute("project", project);
        FileUploadController f = new FileUploadController();
        f.createDir(u.getId(), project.getLocalFiles());
        boolean r = (Boolean) session.getAttribute("display");

        if (r) {
            display = true;
        }
        //setProject(new Project());
    }

    public void upload(FileUploadEvent event) throws EmailException {
        FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        FileUploadController f = new FileUploadController();
        try {
            f.copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }

    public int getSelectCategory() {
        return SelectCategory;
    }

    public void setSelectCategory(int SelectCategoryId) {
        this.SelectCategory = SelectCategoryId;
    }

    public TreeNode getAllFilesFromDirectory() {
        root = new DefaultTreeNode("root", null);
        if (!display) {
            return root;
        }

        TreeNode defaultFolder = new DefaultTreeNode(project.getName(), root);

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        User u = (User) session.getAttribute("user");
        File fileFinder = new File("/home/odiar/Public/file/" + u.getEmail() + "/" + project.getName() + "/");


        FilenameFilter filter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".png");
            }
        };

        File[] allFiles = fileFinder.listFiles(filter);

        if (allFiles == null) {
            allFiles = new File[0];
        }
        for (File file : allFiles) {
            TreeNode archive = new DefaultTreeNode("picture", file.getName(), defaultFolder);
        }

        return root;
    }

    public TreeNode getRoot() {
        return getAllFilesFromDirectory();
    }

    public void DeleteSelectedFile(String archiveName) {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        String action = (String) params.get("nameArchive");
        File f = new File("/home/odiar/Public/file/odair" + action); //old <C:/arquivos/alex/>
        f.delete();
    }

    public boolean isDisplay() {
        return display;
    }

    public void setDisplay(boolean display) {
        this.display = display;
    }

    public void setNoDisplay() {
        this.display = false;
    }

    public String prepareUpdate() {
        project = (Project) (listProject.getRowData());
        return "updateProject";
    }

    public DataModel getListProject() {
        List<Project> list = new ProjectDAO().list();
        listProject = new ListDataModel(list);
        return listProject;
    }
}
